import { NotFound, Forbidden } from 'lin-mizar';
import Sequelize from 'sequelize';
import { Course } from '../model/course';

class CourseDao {
  async getCourse(id) {
    const course = await Course.findOne({
      where: {
        id
      }
    });
    return course;
  }

  async getCourse(id) {
    const course = await Course.findOne({
      where: {
        id
      }
    });

    return course;
  }

  async getCourseByKeyword(q) {
    const course = await Course.findOne({
      where: {
        title: {
          [Sequelize.Op.like]: `%${q}%`
        }
      }
    });
    return course;
  }

  async getCourses() {
    const courses = await Course.findAll();
    return courses;
  }

  async createCourse(v) {
    const course = await Course.findOne({
      where: {
        title: v.get('body.title')
      }
    });
    if (course) {
      throw new Forbidden({
        code: 10240
      });
    }
    const cs = new Course();
    cs.title = v.get('body.title');
    cs.author = v.get('body.author');
    cs.summary = v.get('body.summary');
    cs.image = v.get('body.image');
    await cs.save();
  }

  async updateCourse(v, id) {
    const course = await Course.findByPk(id);
    if (!course) {
      throw new NotFound({
        code: 10022
      });
    }
    course.title = v.get('body.title');
    course.author = v.get('body.author');
    course.summary = v.get('body.summary');
    course.image = v.get('body.image');
    await course.save();
  }

  async deleteCourse(id) {
    const course = await Course.findOne({
      where: {
        id
      }
    });
    if (!course) {
      throw new NotFound({
        code: 10022
      });
    }
    course.destroy();
  }
}

export { CourseDao };
